package com.spingboot.study.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    // 切点：匹配 controller 包及子包下所有 public 方法
    @Pointcut("execution(public * com.spingboot.study.controller..*(..))")
    public void controllerMethods() {}

    // 环绕通知：可在方法执行前后做处理
    @Around("controllerMethods()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 获取方法名
        String methodName = joinPoint.getSignature().toShortString();
        // 获取参数
        Object[] args = joinPoint.getArgs();

        System.out.println("【日志】调用方法: " + methodName);
        System.out.println("【日志】入参: " + Arrays.toString(args));

        Object result;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
        } catch (Exception e) {
            System.out.println("【日志】方法异常: " + e.getMessage());
            throw e;
        }

        long endTime = System.currentTimeMillis();
        System.out.println("【日志】返回值: " + result);
        System.out.println("【日志】耗时: " + (endTime - startTime) + " ms");

        return result;
    }
}
